
/*
    pbrt source code Copyright(c) 1998-2012 Matt Pharr and Greg Humphreys.

    This file is part of pbrt.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are
    met:

    - Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.

    - Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
    IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
    TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
    PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
    HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

 */


#include "stdafx.h"
#include "integrators/bipath.h"
#include "scene.h"
#include "intersection.h"
#include "paramset.h"


BipathIntegrator::BipathIntegrator(int md) : PathIntegrator(md) {
}


void BipathIntegrator::RequestSamples(Sampler *sampler, Sample *sample,
                                    const Scene *scene) {
	rayOffset = sample->Add1D(5);
	lightPathNumOffset = sample->Add1D(1);
	lightNumOffset = sample->Add1D(maxDepth);
    lightSampleOffset = LightSampleOffsets(maxDepth, sample);
    bsdfSampleOffset = BSDFSampleOffsets(maxDepth, sample);
    pathSampleOffset = BSDFSampleOffsets(maxDepth, sample);
	lightPathSampleOffset = BSDFSampleOffsets(maxDepth, sample);
}


IntegrationResult BipathIntegrator::Li(const Scene *scene, 
	const Renderer *renderer, const RayDifferential &ray, 
	const Intersection &isect, const Sample *sample, RNG &rng, 
	MemoryArena &arena) const {
    // Declare common path integration variables
    Spectrum L(0.f), escapedAlpha(0.f);
	RayDifferential escapedRay;
    bool prevSpecular = true;
	PathData data(scene, renderer, rng, arena);

	float lightRayPdf;
	RayDifferential lightRay;
	Spectrum lightAlpha = SampleLight(data, sample, &lightRayPdf, 
		&lightRay);
	if (lightAlpha.IsBlack() || lightRayPdf == 0.f) {
		return PathIntegrator::Li(scene, renderer, ray, isect, sample, rng, arena);
	}

	PathVertex *cameraPath = new PathVertex[maxDepth];
	PathVertex *lightPath = new PathVertex[maxDepth];
	int cameraPathLength = GeneratePath(data, ray, isect, sample, cameraPath, 
		&escapedRay, &escapedAlpha);
	int lightPathLength = GenerateLightPath(data, lightRay, sample, lightAlpha, 
		lightPath);

	// Compute number of specular vertices for each path length
	int nVerts = cameraPathLength + lightPathLength + 2;
	int *nSpecularVertices = new int[nVerts];
	GetNumSpecularVertices(cameraPath, lightPath, cameraPathLength, 
		lightPathLength, nSpecularVertices);

	for (int i = 0; i < cameraPathLength; ++i) {
		// Initialize basic variables for camera path vertex
		const PathVertex &vc = cameraPath[i];

		// Add emitted light from vertex if appropriate
		if (prevSpecular)
			L += vc.alpha * vc.isect.Le(vc.wPrev);

		// Add direct illumination for path vertex
		Spectrum Ld = DirectLightingVertex(data, sample, i, vc);

		prevSpecular = vc.specularBounce;
		L += Ld / (i + 1 - nSpecularVertices[i + 1]);

		if (!vc.specularBounce) {
			// Loop over light path vertices and connect to camera vertex
			for (int j = 0; j < lightPathLength; ++j) {
				L += LightPathL(data, *sample, lightPath, vc, nSpecularVertices,
					i, j);
			}
		}
	}

	// Add contribution of escaped ray, if any
	if (!escapedAlpha.IsBlack() && prevSpecular)
	for (uint32_t i = 0; i < scene->lights.size(); ++i)
		L += (escapedAlpha) * scene->lights[i]->Le(escapedRay);
	
	delete[] nSpecularVertices;
	delete[] cameraPath;
	delete[] lightPath;
	return L;
}


Spectrum BipathIntegrator::SampleLight(PathData &data, const Sample *sample, 
	float *lightRayPdf, Ray *lightRay) const {
	Normal Nl;
	float lightPdf;

	uint32_t lightNum = lightDistribution->SampleDiscrete(
		sample->oneD[lightPathNumOffset][0], &lightPdf);
	const Light *light = data.scene->lights[lightNum];

	LightSample lrs(
		sample->oneD[rayOffset][0], sample->oneD[rayOffset][1], 
		sample->oneD[rayOffset][2]);

	Spectrum lightWt = light->Sample_L(data.scene, lrs, sample->oneD[rayOffset][3], 
		sample->oneD[rayOffset][4], sample->time, lightRay, &Nl, lightRayPdf);
	lightWt *= AbsDot(Normalize(Nl), lightRay->d) / (*lightRayPdf * (lightPdf));

	return lightWt;
}


void BipathIntegrator::GetNumSpecularVertices(PathVertex* cameraPath, 
	PathVertex* lightPath, int cameraPathLength, int lightPathLength, 
	int *nSpecularVertices) const {
	int nVerts = cameraPathLength + lightPathLength + 2;
	memset(nSpecularVertices, 0, nVerts * sizeof(int));
	for (int i = 0; i < cameraPathLength; ++i)
	for (int j = 0; j < lightPathLength; ++j)
	if (cameraPath[i].specularBounce || lightPath[j].specularBounce)
		++nSpecularVertices[i + j + 2];
}


Spectrum BipathIntegrator::LightPathL(PathData &data, const Sample &sample, 
	PathVertex* lightPath, const PathVertex &vc, 
	int *nSpecularVertices, int cameraPathIdx, int lightPathIdx) const {
	const Point &pc = vc.bsdf->dgShading.p;
	const Normal &nc = vc.bsdf->dgShading.nn;
	const PathVertex &vl = lightPath[lightPathIdx];
	const Point &pl = vl.bsdf->dgShading.p;
	const Normal &nl = vl.bsdf->dgShading.nn;
	Spectrum L(0.f);

	if (!vl.specularBounce) {
		// Compute contribution between camera and light vertices
		Vector w = Normalize(pl - pc);
		Spectrum fc = vc.bsdf->f(vc.wPrev, w) * (1 + vc.nSpecularComponents);
		Spectrum fl = vl.bsdf->f(-w, vl.wPrev) * (1 + vl.nSpecularComponents);
		Ray r(pc, pl - pc, 1e-3f, .999f, sample.time);

		if (!fc.IsBlack() && !fl.IsBlack() && !data.scene->IntersectP(r)) {
			// Compute weight for bidirectional path, _pathWt_
			int pathIdx = cameraPathIdx + lightPathIdx + 2;
			float pathWt = 1.f / (pathIdx - nSpecularVertices[pathIdx]);
			float G = AbsDot(nc, w) * AbsDot(nl, w) / DistanceSquared(pl, pc);
			L += (vc.alpha * fc * G * fl * vl.alpha) * pathWt;
		}
	}
	return L;
}


uint32_t BipathIntegrator::GenerateLightPath(PathData &data, 
	const RayDifferential lightRay, const Sample* sample, const Spectrum &a, 
	PathVertex *path) const {
	// Declare common path integration variables
	RayDifferential ray(lightRay);
	Spectrum alpha(a);

	int length = 0;
	for (; length < maxDepth; length++) {
		// Try to generate next vertex of ray path
		PathVertex *v = &path[length];
		if (!data.scene->Intersect(ray, &v->isect)) break;
		SavePathVertexInfo(v, ray, alpha, data.arena);

		// Sample BSDF to get new path direction
		float pdf;
		BxDFType flags;
		BSDFSample BSDFSampleOut = BSDFSample(sample, lightPathSampleOffset, 
			length);
		Spectrum f = v->bsdf->Sample_f(-ray.d, &v->wNext, BSDFSampleOut, &pdf,
			BSDF_ALL, &flags);
		v->specularBounce = (flags & BSDF_SPECULAR) != 0;
		v->nSpecularComponents = v->bsdf->NumComponents(BxDFType(BSDF_SPECULAR |
			BSDF_REFLECTION | BSDF_TRANSMISSION));

		if (f.IsBlack() || pdf == 0. || !RussianRoulette(data, *v, f, pdf, &ray,
			&alpha)) {
			return length + 1;
		}
	}
	return length;
}


BipathIntegrator *CreateBipathSurfaceIntegrator(
	const ParamSet &params) {
    int maxDepth = params.FindOneInt("maxdepth", 5);
	return new BipathIntegrator(maxDepth);
}
